/*!
 * jQuery.Huifold.js v2.1 折叠
 * http://www.h-ui.net/
 * Created & Modified by guojunhui
 * Date modified 2024.09.12
 * Copyright 2017-2024 郭俊辉 All rights reserved.
 * Licensed under MIT license.
 * http://opensource.org/licenses/MIT
 * 使用方法：
  $("#Huifold-demo1").Huifold({
    item: '.item',
    titCell:'h4',
    mainCell:'.info',
    type:1,
    trigger:'click',
    className:"selected",
    speed:"first",
  });
 */
!function($) {
  $.fn.Huifold = function(options) {
    // 确保options是一个对象
    options = (typeof options === 'object' && options !== null) ? options : {};

    var defaults = {
      titCell: ".hui-fold-header",
      mainCell: ".hui-fold-content",
      type: 1,  // 1 只打开一个，可以全部关闭; 2 必须有一个打开; 3 可打开多个
      trigger: "click",
      className: "selected",
      speed: "normal",
      openKeys: [] // 默认打开
    };
    var settings = $.extend({}, defaults, options);

    return this.each(function() {
      var $this = $(this);
      var $titCell = $this.find(settings.titCell);
      var $mainCell = $this.find(settings.mainCell);

      // 初始化默认打开的折叠项
      if (settings.openKeys && settings.openKeys.length > 0) {
        $.each(settings.openKeys, function(i, key) {
          var $header = $titCell.eq(key);
          $header.addClass(settings.className);
          $mainCell.eq(key).show();
          $header.find("b").html("-");
        });
      }

      // 事件绑定
      $titCell.on(settings.trigger, function() {
        var $header = $(this);
        var $content = $header.next(settings.mainCell);
        var contentVisible = $content.is(":visible");

        if (contentVisible) {
          if (settings.type === 2) {
            return false; // 如果是必须有一个打开的类型，则不能关闭
          } else {
            $content.slideUp(settings.speed);
            $header.removeClass(settings.className);
            $header.find("b").html("+");
          }
        } else {
          if (settings.type === 3) {
            $content.slideDown(settings.speed);
            $header.addClass(settings.className);
            $header.find("b").html("-");
          } else {
            $mainCell.slideUp(settings.speed);
            $titCell.removeClass(settings.className);
            $titCell.find("b").html("+");
            $content.slideDown(settings.speed);
            $header.addClass(settings.className);
            $header.find("b").html("-");
          }
        }
      });
    });
  };
}(window.jQuery);